package com.ychs.lawyer.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ychs.lawyer.bean.Constant;
import com.ychs.lawyer.bean.ResultCode;
import com.ychs.lawyer.exception.BussinessException;
import com.ychs.lawyer.vo.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: clh
 * @Date: 2024/08/14/16:34
 * @Description:
 */

@Component
public class GetLoginUser {

    private  static StringRedisTemplate stringRedisTemplate;

    @Autowired
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        GetLoginUser.stringRedisTemplate = stringRedisTemplate;
    }
//    获取当前登录的用户
    public static LoginUser getUser() {
        HttpServletRequest request = RequestUtils.getRequest();
        String token = request.getHeader("token");
//        判断是否为空
        if (StrUtil.isBlank(token)) {
            throw new BussinessException(ResultCode.ERROR_TOKEN);
        }
            String uuid = null;
//        解析过程中 很有可能出异常
        try {
            Claims claims = JwtUtils.parseToken(token);
            uuid = (String) claims.get("uuid");
//            去redis中取当前用户
        } catch (Exception e) {
            e.printStackTrace();
        }
        Boolean isExists = stringRedisTemplate.hasKey(Constant.LOGIN_USER_UUD + uuid);
        if(!isExists) {
            throw new BussinessException(ResultCode.ERROR_TOKEN);
        }
        else {
            String loginUserStr = stringRedisTemplate.opsForValue().get(Constant.LOGIN_USER_UUD + uuid);
            return JSONUtil.toBean(loginUserStr,LoginUser.class);
        }


    }
}
